//
//  LLGComposeTextView.swift
//  Weibo30LLG
//
//  Created by 李龙 on 16/8/17.
//  Copyright © 2016年 lilong. All rights reserved.
//

import UIKit

//文本视图
@IBDesignable
class LLGComposeTextView: UITextView {
    
    //占位文字
    private lazy var placeHolderLabel: UILabel = {
    
        let label = UILabel()
        label.font = UIFont.systemFontOfSize(12)
        label.textColor = UIColor.lightGrayColor()
        label.text = "听说下雨天音乐跟辣条更配哟~"
        
        label.numberOfLines = 0

        return label
    }()
    
    //外界设置占位文字
    @IBInspectable var placeHolder: String? {
    
        didSet {
        
            placeHolderLabel.text = placeHolder
        }
    }
    
    //重写font
    override var font: UIFont? {
    
        didSet {
        
            if font != nil {
            
                placeHolderLabel.font = font
            }
        }
    }
    
    //重写text
    override var text: String? {
    
        didSet {
            placeHolderLabel.hidden = hasText()
        }
    }
    

    override init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame: frame, textContainer: textContainer)
        
        setupUI()
    }

    // MARK: --加载xib调用
    required init?(coder aDecoder: NSCoder) {
        
        super.init(coder: aDecoder)
        
        setupUI()
    }

    // MARK: --添加控件,设置约束
    private func setupUI() {
        
        //注册通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "textChange", name: UITextViewTextDidChangeNotification, object: nil)
        
        
        addSubview(placeHolderLabel)
        
        //使用系统约束
        placeHolderLabel.translatesAutoresizingMaskIntoConstraints = false
        
        addConstraint(NSLayoutConstraint(item: placeHolderLabel, attribute: .Width, relatedBy: .Equal, toItem: self, attribute: .Width, multiplier: 1, constant: -10))
    }
    
    // MARK: --监听文字改变
    @objc private func textChange() {
    
        placeHolderLabel.hidden = hasText()
    }
    
    // MARK: --给子控件设置约束
    override func layoutSubviews() {
        
        super.layoutSubviews()
        
        placeHolderLabel.frame.origin.x = 5
        placeHolderLabel.frame.origin.y = 7
    }
    
    
    deinit {
    
        //移除通知
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
}
